<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="../js/vue-2.6.12.js"></script>
</head>
<body>
  <div id="app">
    <my-table @userdetail="userdetail" :newuser="userList"></my-table>
    <hr/>
    <update-form :userdetail="user" @changeuser="changeuser"></update-form>
  </div>
  <template id="my-table">
    <table border="1">
        <thead>
            <tr>
                <th>id</th>
                <th>name</th>
                <th>age</th>
                <th>operation</th>
            </tr>
        </thead>
        <tbody>
            <tr v-for="(u,index) in newuser" :key="u.id">
                <td>{{u.id}}</td>
                <td>{{u.name}}</td>
                <td>{{u.age}}</td>
                <td>
                    <button @click="emitUser(index)">更新</button>
                </td>
            </tr>
        </tbody>
    </table>
  </template>

  <template id="update-form">
    <form action="" @submit.prevent="changeUser">
        <input type="hidden" v-model="userdetail.id" >
        用户名: <input type="text" v-model="userdetail.name"> <br>
        年龄: <input type="number" v-model="userdetail.age"> <br>
        <input type="submit" value="更新">
    </form>
  </template>
  <script>
    const myTable={
      template:"#my-table",
      methods:{
        emitUser:function(index){
          this.$emit("userdetail",this.newuser[index]);
        }
      },
      props:["newuser"]
    };
    const updateForm={
      template:"#update-form",
      props:["userdetail"],
      methods:{
        changeUser:function(){
          this.$emit("changeuser",this.userdetail);
        }
      }
    }
    new Vue({
      el:"#app",
      data:{
        user:{},
        userList:[{id:1,name:"zs",age:20},{id:2,name:"ls",age:22},{id:3,name:"ww",age:21}]
      },
      components:{
        myTable,
        updateForm
      },
      methods:{
        userdetail:function(user){
          this.user = structuredClone(user);
        },
        changeuser(user){
          this.$set(this.userList,user.id-1,structuredClone(user));
        }
      }
    });
  </script>
</body>
</html>